# oschooser.pl
# Read the list of operating systems and ask the user to choose
# an OS and version

$| = 1;

($oslist, $out, $auto) = @ARGV;
open(OS, $oslist) || die "failed to open $oslist : $!";
while(<OS>) {
	chop;
	if (/^([^\t]+)\t+([^\t]+)\t+(\S+)\t+(\S+)\t*(.*)$/) {
		push(@list, [ $1, $2, $3, $4, $5 ]);
		push(@names, $1) if (!$donename{$1}++);
		}
	}
close(OS);

if ($auto) {
	# Try to guess the OS name and version
	if (-r "/etc/.issue") {
		$etc_issue = `cat /etc/.issue`;
		}
	elsif (-r "/etc/issue") {
		$etc_issue = `cat /etc/issue`;
		}
	$uname = `uname -a`;
	foreach $o (@list) {
		if ($o->[4] && eval $o->[4]) {
			# Got a match!
			$ver = $o;
			last;
			}
		}
	if (!$ver) {
		if ($auto == 1) {
			# Failed .. give up
			print "Failed to detect operating system\n";
			exit 1;
			}
		else {
			# Ask the user
			$auto = 0;
			}
		}
	}

if (!$auto) {
	# ask for the operating system name
	$dashes = "-" x 75;
	print <<EOF;
For Webmin to work properly, it needs to know which operating system
type and version you are running. Please select your system type by
entering the number next to it from the list below
$dashes
EOF
	for($i=0; $i<@names; $i++) {
		printf " %2d) %-34s ", $i+1, $names[$i];
		print "\n" if ($i%2);
		}
	print "\n" if ($i%2);
	print $dashes,"\n";
	print "Operating system: ";
	chop($osnum = <STDIN>);
	if ($osnum !~ /^\d+$/) {
		print "ERROR: You must enter the number next to your operating\n";
		print "system, not its name or version number.\n\n";
		exit 9;
		}
	if ($osnum < 1 || $osnum > @names) {
		print "ERROR: $osnum is not a valid operating system number.\n\n";
		exit 10;
		}
	print "\n";

	# Ask for the operating system version
	$name = $names[$osnum-1];
	@vers = grep { $_->[0] eq $name } @list; 
	print <<EOF;
Please choose which version of $name you are running, by entering
the number next to it from the list below
$dashes
EOF
	for($i=0; $i<@vers; $i++) {
		printf " %2d) %-34s ", $i+1, $name." ".$vers[$i]->[1];
		print "\n" if ($i%2);
		}
	print "\n" if ($i%2);
	print $dashes,"\n";
	print "Version: ";
	chop($vnum = <STDIN>);
	if ($vnum !~ /^\d+$/) {
		print "ERROR: You must enter the number next to your operating\n";
		print "system version, not its name or version number.\n\n";
		exit 9;
		}
	if ($vnum < 1 || $vnum > @vers) {
		print "ERROR: $vnum is not a valid operating system number.\n\n";
		exit 10;
		}
	print "\n";
	$ver = $vers[$vnum-1];
	}

# Write the name, version and real name and version to a file
open(OUT, ">$out");
print OUT "os_type='",$ver->[2],"'\n";
print OUT "os_version='",$ver->[3],"'\n";
print OUT "real_os_type='",$ver->[0],"'\n";
print OUT "real_os_version='",$ver->[1],"'\n";
close(OUT);
